package com.xpec.c4.db.usertype;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;

import com.ms.db.usertype.BasicToString;

public class MapStringStringToString extends BasicToString{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6172210049226122332L;

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		/*
		 * if (x == y) return true;
		 */
		if (x != null && y != null) {
			Map<?, ?> xMap = (Map<?, ?>) x;
			Map<?, ?> yMap = (Map<?, ?>) y;
			if (xMap.size() != yMap.size())
				return false;
			Set<?> keys = xMap.keySet();
			for (Object key : keys) {
				Object str1 = xMap.get(key);
				Object str2 = yMap.get(key);
				if (!str1.equals(str2))
					return false;
			}
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected String assemble(Object obj) {
		Map map=(Map)obj;
        StringBuffer strBuf = new StringBuffer();  
        Set keys=map.keySet();
        for(Object key:keys){
        	strBuf.append(String.valueOf(key)+SPLITTER);
        	strBuf.append(String.valueOf(map.get(key))+SPLITTER);
        }
        if(strBuf.length()>0){
        	return strBuf.substring(0, strBuf.length()-1);
        }
        return strBuf.toString();   
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Object parse(String value) {
		if(value==null){
			return null;
		}
    	Map map = new HashMap(); 
    	if(value.length()<=0){
    		return map;
    	}
        String[] strs = value.split(SPLITTER);   
          
        for (int i = 0; i < strs.length; i+=2) {   
            map.put(strs[i], i+1<strs.length?strs[i+1]:"");
        }   
        return map;   
	}

	@Override
	public Class<?> returnedClass() {
		return Map.class;
	}

	@Override
	public int[] sqlTypes() {
		return CLOB_TYPES;
	}

}
